/*
 * Main.java
 *
 * Created on __DATE__, __TIME__
 */

package zzj;

import java.awt.Dialog;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.Enumeration;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 * 
 * @author DaRKeViL
 */
public class Main extends javax.swing.JFrame {
	private SqliteDao sqldDao = new SqliteDao();
	private WhereIsMovie wim = new WhereIsMovie();

	/** Creates new form Main */
	public Main() {
		initComponents();
		searchMovieInfoData();
		getConfData();

	}

	// GEN-BEGIN:initComponents
	// <editor-fold defaultstate="collapsed" desc="Generated Code">
	private void initComponents() {

		jScrollPane1 = new javax.swing.JScrollPane();
		movieInfoTable = new javax.swing.JTable();
		jLabel1 = new javax.swing.JLabel();
		searchTextField = new javax.swing.JTextField();
		searchButton = new javax.swing.JButton();
		addButton = new javax.swing.JButton();
		scanButton = new javax.swing.JButton();
		setFileTypeButton = new JButton();
		setPlayerButton = new JButton();
		jScrollPane2 = new javax.swing.JScrollPane();
		confTable = new javax.swing.JTable();
		editButton = new javax.swing.JButton();
		delButton = new javax.swing.JButton();
		cleanButton = new JButton();

		setTitle("电影有没有？ -_-! Develop By DaRKeViL @_@ ");
		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		jScrollPane1.setViewportView(movieInfoTable);

		movieInfoTable.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				if (evt.getClickCount() == 2) {
					openMovie();
				}
			}
		});

		jLabel1.setText("\u7535\u5f71\u540d\u79f0:");

		searchTextField.setText("");

		searchButton.setText("\u67e5\u627e");
		searchButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				searchButtonMouseClicked(evt);
			}
		});

		cleanButton.setText("清除");
		cleanButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				cleanButtonMouseClicked(evt);
			}
		});

		addButton.setText("\u65b0\u589e\u8def\u5f84");
		addButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				addButtonMouseClicked(evt);
			}
		});

		scanButton.setText("\u626b\u63cf\u7535\u5f71");
		scanButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				scanButtonMouseClicked(evt);
			}
		});

		jScrollPane2.setViewportView(confTable);

		editButton.setText("\u7f16\u8f91\u8def\u5f84");
		editButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				editButtonMouseClicked(evt);
			}
		});

		delButton.setText("\u5220\u9664\u8def\u5f84");
		delButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				delButtonMouseClicked(evt);
			}
		});

		setFileTypeButton.setText("设置文件类型");
		setFileTypeButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				setFileTypeButtonMouseClicked(evt);
			}
		});

		setPlayerButton.setText("设置播放器路径");
		setPlayerButton.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				setPlayerButtonMouseClicked(evt);
			}
		});

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.LEADING)
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										jLabel1)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										searchTextField,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										300,
																										Short.MAX_VALUE)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										searchButton,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										javax.swing.GroupLayout.PREFERRED_SIZE)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										cleanButton)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										setPlayerButton)
																								.addPreferredGap(
																										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																								.addComponent(
																										setFileTypeButton)
																								.addGap(12,
																										12,
																										12)
																								.addComponent(
																										scanButton,
																										javax.swing.GroupLayout.DEFAULT_SIZE,
																										284,
																										284))
																				.addGroup(
																						layout.createSequentialGroup()
																								.addComponent(
																										jScrollPane1,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										javax.swing.GroupLayout.PREFERRED_SIZE,
																										Short.MAX_VALUE)
																								.addGap(12,
																										12,
																										12)
																								.addGroup(
																										layout.createParallelGroup(
																												javax.swing.GroupLayout.Alignment.LEADING)
																												.addGroup(
																														layout.createSequentialGroup()
																																.addComponent(
																																		addButton,
																																		90,
																																		90,
																																		90)
																																.addPreferredGap(
																																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																.addComponent(
																																		editButton,
																																		90,
																																		90,
																																		90)
																																.addPreferredGap(
																																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																																.addComponent(
																																		delButton,
																																		90,
																																		90,
																																		90))
																												.addComponent(
																														jScrollPane2,
																														284,
																														284,
																														284))))
																.addGap(12, 12,
																		12))
								/*
								 * .addGroup( layout.createSequentialGroup())
								 */)));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(
														jLabel1,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														20,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(scanButton)
												.addComponent(setPlayerButton)
												.addComponent(setFileTypeButton)
												.addComponent(cleanButton)
												.addComponent(searchButton)
												.addComponent(
														searchTextField,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE))
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.RELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING)
												.addGroup(
														layout.createSequentialGroup()
																.addGroup(
																		layout.createParallelGroup(
																				javax.swing.GroupLayout.Alignment.BASELINE)
																				.addComponent(
																						addButton)
																				.addComponent(
																						editButton)
																				.addComponent(
																						delButton))
																.addPreferredGap(
																		javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																.addComponent(
																		jScrollPane2,
																		javax.swing.GroupLayout.DEFAULT_SIZE,
																		276,
																		Short.MAX_VALUE))
												.addComponent(
														jScrollPane1,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														Short.MAX_VALUE))
								.addContainerGap()));

		pack();
	}// </editor-fold>

	protected void setFileTypeButtonMouseClicked(MouseEvent evt) {
		// TODO Auto-generated method stub
		String fileType = wim.getProperties("fileType");
		String s = JOptionPane.showInputDialog("文件类型", fileType);
		if(s!=null && s!="null" && !"null".equals(s) && !"".equals(s)){
		wim.setProperties("fileType", s);
		}
	}

	private void setPlayerButtonMouseClicked(MouseEvent evt) {
		// TODO Auto-generated method stub
		JFileChooser fileChooser = new JFileChooser();

		fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
		int returnval = fileChooser.showOpenDialog(Main.this);
		if (returnval == JFileChooser.APPROVE_OPTION) {
			File path = fileChooser.getSelectedFile();
			wim.setProperties("playerPath", path.toString());
		}

	}

	private void openMovie() {
		// TODO Auto-generated method stub
		int row = movieInfoTable.getSelectedRow();
		int cols = movieInfoTable.getColumnCount();
		int pathCol = 0;
		int volcol = 0; // 卷序列号所在列
		String curVolSerial = "";
		String path = "";
		for (int col = 0; col < cols; col++) {
			if ("路径".equals(movieInfoTable.getColumnName(col))) {
				pathCol = col;
			} else if ("卷序列号".equals(movieInfoTable.getColumnName(col))) {
				volcol = col;
			}
		}
		curVolSerial = movieInfoTable.getValueAt(row, volcol).toString();
		String playerPath = wim.getProperties("playerPath");
		path = movieInfoTable.getValueAt(row, pathCol).toString();
		if ("未连接".equals(wim.isPathVaild(path, curVolSerial))) {
			JOptionPane
					.showMessageDialog(
							Main.this,
							"小妹我找不到这个文件么~~，人家真的是找不到么~~，也许~是你没有把盘插到人家上面呢~~，\n你要是把盘插上了，人家就给你么么哒~~",
							"错误", JOptionPane.ERROR_MESSAGE);
			return;
		}
		try {

			Process proc = Runtime.getRuntime().exec(
					playerPath + "  \"" + path + "\"");
		} catch (Exception e) {
			// TODO: handle exception
			System.err.println(e.getClass().getName() + ": " + e.getMessage());
			e.printStackTrace();
		}

	}

	// GEN-END:initComponents

	// 查询单击
	private void searchButtonMouseClicked(java.awt.event.MouseEvent evt) {
		// TODO add your handling code here:
		searchMovieInfoData();

	}

	private void cleanButtonMouseClicked(java.awt.event.MouseEvent evt) {
		// TODO add your handling code here:
		searchTextField.setText("");
		searchMovieInfoData();

	}

	private void addButtonMouseClicked(java.awt.event.MouseEvent evt) {
		// TODO add your handling code here:
		addPath();
		getConfData();
	}

	// 扫描硬盘
	private void scanButtonMouseClicked(java.awt.event.MouseEvent evt) {
		// TODO add your handling code here:
		int rows = confTable.getRowCount();
		int cols = confTable.getColumnCount();
		int pathcol = 0; // 路径所在列
		int volcol = 0; // 卷序列号所在列
		int isVaildCol = 0;
		int volNameCol = 0; // 卷标列
		String path = "";
		String volSerial = "";
		String volName = "";
		JProgressBar jpb = new JProgressBar();

		getConfData();

		for (int col = 0; col < cols; col++) {
			if ("扫描路径".equals(confTable.getColumnName(col))) {
				pathcol = col;
			} else if ("卷的序列号".equals(confTable.getColumnName(col))) {
				volcol = col;
			} else if ("是否连接".equals(confTable.getColumnName(col))) {
				isVaildCol = col;
			}
		}
		for (int row = 0; row < rows; row++) {
			if ("已连接".equals(confTable.getValueAt(row, isVaildCol))) {
				path = confTable.getValueAt(row, pathcol).toString();
				volSerial = confTable.getValueAt(row, volcol).toString();
				volName = confTable.getValueAt(row, volNameCol).toString();
				// System.out.println(row + "   "
				// + confTable.getValueAt(row, pathcol).toString());
				wim.scanMovieInfo(path, volSerial, volName);
			}
		}
		searchMovieInfoData();
		System.gc();
	}

	private void editButtonMouseClicked(java.awt.event.MouseEvent evt) {
		int row = confTable.getSelectedRow();
		int cols = confTable.getColumnCount();
		int pathcol = 0; // 路径所在列
		int volcol = 0; // 卷序列号所在列
		int isVaildCol = 0;
		int volNameCol = 0; // 卷标列
		String volSerial = "";
		String oldPath = "";
		for (int col = 0; col < cols; col++) {
			if ("扫描路径".equals(confTable.getColumnName(col))) {
				pathcol = col;
			} else if ("卷的序列号".equals(confTable.getColumnName(col))) {
				volcol = col;
			} else if ("是否连接".equals(confTable.getColumnName(col))) {
				isVaildCol = col;
			} else if ("卷标".equals(confTable.getColumnName(col))) {
				volNameCol = col;
			}
		}
		if (row == -1) {
			JOptionPane.showMessageDialog(Main.this, "请选择需要编辑的行", "错误",
					JOptionPane.ERROR_MESSAGE);
			return;
		} else {
			JFileChooser fileChooser = new JFileChooser();
			volSerial = confTable.getValueAt(row, volcol).toString();
			oldPath = confTable.getValueAt(row, pathcol).toString();
			fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
			int returnval = fileChooser.showOpenDialog(Main.this);
			if (returnval == JFileChooser.APPROVE_OPTION) {
				File path = fileChooser.getSelectedFile();
				wim.delPath(oldPath, volSerial);
				wim.addPath(path);
			}
		}
		getConfData();

	}

	private void delButtonMouseClicked(java.awt.event.MouseEvent evt) {
		int row = confTable.getSelectedRow();
		int cols = confTable.getColumnCount();
		int pathcol = 0; // 路径所在列
		int volcol = 0; // 卷序列号所在列
		int isVaildCol = 0;
		int volNameCol = 0; // 卷标列
		String path = "";
		String volSerial = "";
		for (int col = 0; col < cols; col++) {
			if ("扫描路径".equals(confTable.getColumnName(col))) {
				pathcol = col;
			} else if ("卷的序列号".equals(confTable.getColumnName(col))) {
				volcol = col;
			} else if ("是否连接".equals(confTable.getColumnName(col))) {
				isVaildCol = col;
			} else if ("卷标".equals(confTable.getColumnName(col))) {
				volNameCol = col;
			}
		}
		if (row == -1) {
			JOptionPane.showMessageDialog(Main.this, "请选择需要删除的行", "错误",
					JOptionPane.ERROR_MESSAGE);
			return;
		} else {
			volSerial = confTable.getValueAt(row, volcol).toString();
			path = confTable.getValueAt(row, pathcol).toString();
			wim.delPath(path, volSerial);
			searchMovieInfoData();

		}
		getConfData();
	}

	private void addPath() {
		JFileChooser fileChooser = new JFileChooser();

		fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int returnval = fileChooser.showOpenDialog(Main.this);
		if (returnval == JFileChooser.APPROVE_OPTION) {
			File path = fileChooser.getSelectedFile();
			wim.addPath(path);
		}
	}

	// 新增路径单击
	// private void
	// 查询电影信息
	private void searchMovieInfoData() {
		String name = "";
		name = searchTextField.getText();
		TableModel dataModel = wim.searchMovieInfo(name);
		addRowCount2Tittle(dataModel.getRowCount());
		movieInfoTable.setModel(dataModel);
		movieInfoTable.setRowSorter(new TableRowSorter<TableModel>(dataModel));
		movieInfoTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		FitTableColumns(movieInfoTable);

	}

	private void getConfData() {
		TableModel dataModel = wim.getConfData();
		confTable.setModel(dataModel);
		confTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		FitTableColumns(confTable);

	}

	private void addRowCount2Tittle(int n) {
		String title = this.getTitle();
		title = "电影有没有？ -_-! Develop By DaRKeViL @_@ " + "  共" + n + "条   ";
		this.setTitle(title);
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {
			public void run() {
				new Main().setVisible(true);
			}
		});
	}

	// GEN-BEGIN:variables
	// Variables declaration - do not modify
	private javax.swing.JTable confTable;
	private javax.swing.JButton addButton; // 新增路径
	private javax.swing.JButton scanButton; // 扫描硬盘
	private javax.swing.JButton editButton; // 编辑路径
	private javax.swing.JButton delButton; // 删除路径
	private javax.swing.JButton cleanButton; // 清楚查询条件
	private JButton setPlayerButton; // 设置播放器路径
	private JButton setFileTypeButton; // 设置扫描的文件类型
	private javax.swing.JLabel jLabel1;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JScrollPane jScrollPane2;
	private javax.swing.JTable movieInfoTable;
	private javax.swing.JButton searchButton;
	private javax.swing.JTextField searchTextField;

	// private JGrid movieInfoGrid;
	// private JScrollGrid scrollMovieInfoGrid;
	// End of variables declaration//GEN-END:variables

	public void FitTableColumns(JTable myTable) { // 設置table的列寬隨內容調整
		JTableHeader header = myTable.getTableHeader();
		int rowCount = myTable.getRowCount();
		Enumeration columns = myTable.getColumnModel().getColumns();
		while (columns.hasMoreElements()) {
			TableColumn column = (TableColumn) columns.nextElement();
			int col = header.getColumnModel().getColumnIndex(
					column.getIdentifier());
			int width = (int) myTable
					.getTableHeader()
					.getDefaultRenderer()
					.getTableCellRendererComponent(myTable,
							column.getIdentifier(), false, false, -1, col)
					.getPreferredSize().getWidth();
			for (int row = 0; row < rowCount; row++) {
				int preferedWidth = (int) myTable
						.getCellRenderer(row, col)
						.getTableCellRendererComponent(myTable,
								myTable.getValueAt(row, col), false, false,
								row, col).getPreferredSize().getWidth();
				width = Math.max(width, preferedWidth);
			}
			header.setResizingColumn(column);
			column.setWidth(width + myTable.getIntercellSpacing().width);
		}
	}

}